package com.mall.user.mq.delay;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class RegisterSendEmailConsumer {
    private DefaultMQPushConsumer consumer;

    @Autowired
    private JavaMailSender javaMailSender;

    @PostConstruct
    public void init(){
        consumer = new DefaultMQPushConsumer("register_send_email_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt message = list.get(0);
                byte[] body = message.getBody();
                try {
                    String simpleMailMessageStr = new String(body,0,body.length,"utf-8");
                    SimpleMailMessage simpleMailMessage = JSON.parseObject(simpleMailMessageStr, SimpleMailMessage.class);
                    javaMailSender.send(simpleMailMessage);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.subscribe("register_send_email", "*");

            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
